include ApplicationHelper

class ContactsController < ApplicationController
  before_filter :load_session

  load_and_authorize_resource

  private
  def load_session
    @treatments = Treatment.find(:all, :order=>:description)
    @regards= Regard.find(:all, :order=>:description)
    @localusers = User.search_selector("", params[:page])

    # sirve para que el poup de customer sepa donde setar los valores elegidos
    session[:customer_component_id] = 'contact_reference_id'
    session[:customer_component_type] = 'contact_reference_type'
    session[:customer_component_name] = 'contact_reference_name'
    session[:component_user_id] = 'contact_user_id'
    session[:component_user_name] = 'contact_user'


  end

  def check_access
    if !(current_user.role?(:role_admin)) and !(current_user.contact.nil?) and current_user.contact.id != params[:id].to_i
      show_page_access_denied
      return false
    else
      return true
    end
  end

  public

  def show_reference_text
    @reference_class = params[:reference_class]
    render :partial=> 'reference_text' , :layout=>false
  end

  def auto_complete_reference
    puts "entre!"
    @references=[]
    if params[:reference_class] == "Institute"
      @references= Institute.find(:all,:conditions => ["upper(name) like upper(?)", "%#{params["reference_text"]}%"], :order=> :name)
    end
    if params[:reference_class] == "Library"
      @references= Library.find(:all,:conditions => ["upper(name) like upper(?)", "%#{params["reference_text"]}%"], :order=> :name)
    end
    if params[:reference_class] == "LibraryDepartment"
      @references= LibraryDepartment.find(:all,:conditions => ["upper(name) like upper(?)", "%#{params["reference_text"]}%"], :order=> :name)
    end
    if params[:reference_class] == "People"
      @references= People.find(:all,:conditions => ["upper(last_name) like upper(?)", "%#{params["reference_text"]}%"], :order=> :last_name)
    end
    if params[:reference_class] == "Bookshop"
      @references= Bookshop.find(:all,:conditions => ["upper(name) like upper(?)", "%#{params["reference_text"]}%"], :order=> :name)
    end
    if params[:reference_class] == "BookShopDepartment"
      @references= BookshopDepartment.find(:all,:conditions => ["upper(name) like upper(?)", "%#{params["reference_text"]}%"], :order=> :name)
    end
    if params[:reference_class] == "Publisher"
      @references= Publisher.find(:all,:conditions => ["upper(name) like upper(?)", "%#{params["reference_text"]}%"], :order=> :name)
    end
    render :layout=>false
  end

  def selector_contacts_list
      @contacts = Contact.search(params[:search_last_name], params[:page])
      render :partial=>'contacts/selector_contacts_list', :locals => {:search_last_name => params[:search_last_name]}, :layout=>false
  end

  def selector_contacts_list_from_paginate
      @contacts = Contact.search(params[:search_last_name], params[:page])
  end

  def redirect_back
      redirect_back_or_default params[:url]
  end

  def edit_contact_user_sign_in
    contact = Contact.find_by_user_id(current_user.id)
    redirect_to edit_contact_path(contact)
  end

  # GET /contacts
  # GET /contacts.xml
  def index
    save_redirect_back request.request_uri

    search_last_name = params[:search_last_name] || ""
    @reference_class = params[:reference_class]

#    user = User.find(23)
#    user.send_invitation
    
    if @reference_class == "referece_all"
      params[:reference] = nil
    end
    reference_text = params[:reference]

    @collection_reference_class = ["reference_all"].concat(Contact::VALID_REFERENCE_CLASS)

    @contacts = Contact.search(search_last_name, @reference_class, reference_text,  params[:page])

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @contacts }
    end
  end

  # GET /contacts/1
  # GET /contacts/1.xml
  def show
    #hay que controlar que si el usuario tiene el rol cliente solo pueda ver sus datos
    if check_access
      @contact = Contact.find(params[:id])
      respond_to do |format|
        format.html # show.html.erb
        format.xml  { render :xml => @contact }
      end
    end
  end

  # GET /contacts/new
  # GET /contacts/new.xml
  def new
    @contact = Contact.new
    @contact.reference = People.new

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @contact }
    end
  end

  # GET /contacts/1/edit
  def edit
    #hay que controlar que si el usuario tiene el rol cliente solo pueda ver sus datos
    if check_access
      @contact = Contact.find(params[:id])
      if @contact.reference.nil?
         params[:reference_name] = nil
      else
        if @contact.reference_type == 'People'
          params[:reference_name] = "#{t('activerecord.models.people')} - #{@contact.reference.last_name}, #{@contact.reference.first_name}"
        end
        if @contact.reference_type == 'Institute'
          params[:reference_name] = "#{t('activerecord.models.institute')} - #{@contact.reference.name}"
        end
        if @contact.reference_type == 'Library'
          params[:reference_name] = "#{t('activerecord.models.institute')}: #{@contact.reference.institute.name} - #{t('activerecord.models.library')}: #{@contact.reference.name}"
        end
        if @contact.reference_type == 'LibraryDepartment'
          params[:reference_name] =  "#{t('activerecord.models.institute')}: #{@contact.reference.library.institute.name} - #{t('activerecord.models.library')}: #{@contact.reference.library.name} - #{t('activerecord.models.library_department')}: #{@contact.reference.name}"
        end
        if @contact.reference_type == 'Bookshop'
          params[:reference_name] = "#{t('activerecord.models.bookshop')} - #{@contact.reference.name}"
        end
        if @contact.reference_type == 'BookshopDepartment'
          params[:reference_name] = "#{t('activerecord.models.bookshop')}: #{@contact.reference.bookshop.name} - #{t('activerecord.models.bookshop_department')}: #{@contact.reference.name}"
        end
        if @contact.reference_type == 'Publisher'
          params[:reference_name] = "#{t('activerecord.models.publisher')} - #{@contact.reference.name}"
        end
      end
    end
  end

  # POST /contacts
  # POST /contacts.xml
  def create
    puts "params: #{params}"
    @contact = Contact.new(params[:contact])
    respond_to do |format|

      #primero se salva al contacto para validar que todo este ok
      if @contact.save
        flash_message :notice, t('msg_record_successfully_created')

        #en caso de tener que crear un usuario
        if params['create_user'] == 'yes'

          #se crea el usuario (sin contraseña)
          user = User.new
          user.email = @contact.email
          user.roles_mask = Setting.customer_role_id
          user.save(false)
          
          #se asocia al contacto el usuario
          @contact.user = user
          @contact.save

          #se genera el token para la invitacion
          user.invitation_token = Devise.friendly_token
          user.invitation_sent_at = Time.now.utc
          user.save(false)

          #se crea la lista de favoritos del usuario
          WishList.create(:user => user, :name => WishList::TYPE_FAVORITE, :type_list => WishList::TYPE_FAVORITE)

          #se crea el carrito de compras
          WishList.create(:user => user, :name => WishList::TYPE_CART, :type_list => WishList::TYPE_CART)

          #se crea la lista de reservas
          WishList.create(:user => user, :name => WishList::TYPE_RESERVE, :type_list => WishList::TYPE_RESERVE)

          #se envia la invitacion
          user.send_invitation

          flash_message :notice, t('devise.invitations.send_instructions')
        end

        format.html { redirect_to(@contact) }
        format.xml  { render :xml => @contact, :status => :created, :location => @contact }

      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @contact.errors, :status => :unprocessable_entity }
      end
    end
  end

  # PUT /contacts/1
  # PUT /contacts/1.xml
  def update
    @contact = Contact.find(params[:id])

    respond_to do |format|
      if @contact.update_attributes(params[:contact])
        flash_message :notice, t('msg_record_successfully_updated')

        #por las dudas siempre actualizo el mail del usuario asociado al contacto
        user = @contact.user
        if !user.nil?
          user.email = @contact.email
          user.save
        end

        if params['create_user'] == 'yes'

          #se crea el usuario (sin contrasea)
          user = User.new
          user.email = @contact.email
          user.roles_mask = Setting.customer_role_id
          user.save(false)

          #se asocia al contacto el usuario
          @contact.user = user
          @contact.save

          #se genera el token para la invitacion
          user.invitation_token = Devise.friendly_token
          user.invitation_sent_at = Time.now.utc
          user.save(false)

          #se crea la lista de favoritos del usuario
          WishList.create(:user => user, :name => WishList::TYPE_FAVORITE, :type_list => WishList::TYPE_FAVORITE)

          #se crea el carrito de compras
          WishList.create(:user => user, :name => WishList::TYPE_CART, :type_list => WishList::TYPE_CART)

          #se crea la lista de reservas
          WishList.create(:user => user, :name => WishList::TYPE_RESERVE, :type_list => WishList::TYPE_RESERVE)

          #se envia la invitacion
          user.send_invitation

          flash_message :notice, t('devise.invitations.send_instructions')

          format.html { redirect_to(@contact) }
          format.xml  { render :xml => @contact, :status => :created, :location => @contact }

        else
          if (!current_user.role?(:role_admin) && (@contact.profiles.nil? || @contact.profiles.length == 0))
            flash[:notice] = t('contact_profiles.not_contact_profiles')
            format.html { redirect_to(contact_profiles_path) }
            format.xml  { head :ok }
          else
            format.html { redirect_to(@contact) }
            format.xml  { head :ok }
          end
        end
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @contact.errors, :status => :unprocessable_entity }
      end
    end
  end

  # DELETE /contacts/1
  # DELETE /contacts/1.xml
  def destroy
    @contact = Contact.find(params[:id])
    @contact.destroy
    respond_to do |format|
      format.html { redirect_to(contacts_url) }
      format.xml  { head :ok }
    end
  end
end